<template>
  <div class="container">
    <van-nav-bar left-arrow title="搜索中心" @click-left="$router.back()"></van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      v-model.trim="keyword"
      @input="hGetSuggestion_with_jieliu"
    >
      <div slot="action" @click="hSearch">搜索</div>
    </van-search>

    <!-- 联想词 -->
    <van-cell-group v-if="keyword">
      <van-cell
        v-for="(item, idx) in cSuggestion"
        :key="idx"
        icon="search"
        @click="hSearchSuggestion(idx)"
      >
        <div v-html="item"></div>
      </van-cell>
    </van-cell-group>
    <!-- 搜索历史 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell v-for="(item, idx) in history" :key="idx" :title="item">
        <van-icon name="close" @click="hDeleteHistory(idx)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from '@/api/search.js';
import { setItem, getItem } from '@/utils/storage.js';

// 消除魔术数/魔术字符串
const SEARCHISTORY_KEY = 'searchHistory';
export default {
  name: 'SearchResult',
  data () {
    return {
      keyword: '', // 搜索关键字
      suggestion: [],
      history: getItem(SEARCHISTORY_KEY) || []
    };
  },
  computed: {
    cSuggestion () {
      const regexp = new RegExp(this.keyword, 'gi');
      const arr = this.suggestion.map(str => {
        return str.replace(regexp, obj => {
          return `<span style="color: red">${obj}</span>`;
        });
      });
      return arr;
    }
  },
  methods: {
    hDeleteHistory (idx) {
      this.history.splice(idx, 1);
      setItem(SEARCHISTORY_KEY, this.history);
    },
    hSearchSuggestion (idx) {
      this.addHistory(this.suggestion[idx]);
    },
    hSearch () {
      if (this.keyword === '') {
        return;
      }
      this.addHistory(this.keyword);
    },
    addHistory (str) {
      const idx = this.history.findIndex(item => item === str);
      if (idx === -1) {
        this.history.unshift(str);
      }
      setItem(SEARCHISTORY_KEY, this.history);
    },

    // 函数防抖
    hGetSuggestion_with_fangdou () {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(async () => {
        if (this.keyword === '') {
          this.suggestion = [];
          return;
        }
        const res = await getSuggestion(this.keyword);
        this.suggestion = res.data.data.options;
      }, 500);
    },

    // 函数节流(用户体验更好，选他)
    hGetSuggestion_with_jieliu () {
      if (this.timer) {
        return
      }
      this.timer = setTimeout(async () => {
        this.timer = null
        if (this.keyword === '') {
          this.suggestion = [];
          return;
        }
        const res = await getSuggestion(this.keyword);
        this.suggestion = res.data.data.options;
      }, 500);
    }
  }
};
</script>

<style scoped lang='less'></style>
